# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'Allpw-ac73-63286780da79': {  # dwc  支付宝2.8%（50---3000）
        'API_KEY': 'ISsue896883',
        'gateway': 'http://www.4k3d.cn/gopay/putorder',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] is not None and parameter[k] != '':
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    s = 'amount={}&cpid={}&orderId={}&pay_time={}&key={}'.format(
        d['amount'], d['cpid'], d['orderId'], d['pay_time'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('pay_sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("zhifutongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 可选值：W_CODE=微信扫码、W_H5=微信H5、A_CODE=支付宝扫码、A_H5=支付宝H5
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'W_H5'
    elif service == 'alipay':
        payType = 'A_H5'
    else:
        payType = 'A_H5'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('cpid', mch_id),
        ('amount', str(int(pay_amount * 100))),
        ('product', 'charge'),
        ('orderid', str(pay.id)),
        ('describe', 'pay'),
        ('synurl', '{}/pay/api/{}/zhifutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('jumpurl', '{}/pay/api/{}/zhifutongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('payext', _get_pay_type(service)),
        ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("zhifutongpay create date: %s", parameter_dict)
    html_text = _build_form(parameter_dict, _get_gateway(mch_id))
    _LOGGER.info("zhifutongpay create html: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


# SUCCESS
def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("zhifutongpay notify body: %s", request.body)
    verify_notify_sign(data, key)
    pay_id = data['orderId']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('zhifutongpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['pay_code'])
    trade_no = ''
    total_fee = float(data['amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0为成功 其余为失败
    if trade_status == 0:
        _LOGGER.info('zhifutongpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
